<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title + '单据编码'"
    :visible="true"
    width="600px"
    @close="cancel()"
    destroy-on-close
  >
    <div>
      <el-form ref='formTop' :model="formModel" label-width="80px">
        <el-row :gutter="20" style='margin-bottom:10px'>
          <el-col :span="12">
            <el-form-item
              label="编码编号"
              prop="encodeNum"
              :rules="[{ required: true, message: '编码编号不能为空' }]"
            >
              <el-input
                v-model="formModel.encodeNum"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="编码名称"
              prop="encodeName"
              :rules="[{ required: true, message: '编码名称不能为空' }]"
            >
              <el-input
                v-model="formModel.encodeName"
                autocomplete="off"
              />
            </el-form-item>
          </el-col>
        </el-row>
            <el-form-item label="编码说明" prop="encodeDesc">
              <el-input
                v-model="formModel.encodeDesc"
                autocomplete="off"
              />
            </el-form-item>
      </el-form>
      <div class="btnCen">
        <div>
          <el-button type="primary" @click="addCodingRule">新增</el-button>
          <el-button @click='editRule'>编辑</el-button>
          <el-button @click='deleteRule'>删除</el-button>
        </div>
        <div style='lineHeight:36px'>
          设计规则
           <el-tooltip class="item" effect="dark" content="显隐" placement="top">
              <el-button icon="el-icon-s-operation" circle @click="dialogDrawer"></el-button>
           </el-tooltip>
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        stripe
        style="width: 100%; marginbottom: 20px"
        size="small"
        class="tableInfo"
        row-key="id"
        :highlight-current-row="islight"
        @row-click='tableClick'
      >
        <el-table-column label="序号" width="80" align="center" v-if='!childShowHideDate[0].hide'>
          <template slot-scope="scope">
            <span>{{
              scope.$index+1
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="prefixion" label="前缀" align="center" v-if='!childShowHideDate[1].hide'>
          <template slot-scope="scope">
            <span>{{
              options.filter((item)=>{return item.value == scope.row.prefixion})[0].label
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="layout" label="格式" align="center" v-if='!childShowHideDate[2].hide'/>
        <el-table-column prop="stepSize" label="步长" align="center" v-if='!childShowHideDate[3].hide'/>
        <el-table-column prop="initialValue" label="初始值" align="center" v-if='!childShowHideDate[4].hide'/>
        <el-table-column prop="description" label="说明" align="center" v-if='!childShowHideDate[5].hide'/>
      </el-table>
      <div class="button">
        <el-button @click="cancel">取消</el-button>
        <el-button @click="onSaveCode(formModel)" type="primary">确定</el-button>
      </div>
    </div>
    <div v-if="visible">
      <el-dialog
        :close-on-click-modal="false"
        :title="ruleTitle"
        :visible="true"
        width="500px"
        @close="cancel('rule')"
        destroy-on-close
        :append-to-body="true"
      >
        <el-form label-width="80px" :model="formRule" ref='refRule'>
          <el-form-item
            label="前缀"
            prop="prefixion"
            :rules="[{ required: true, message: '前缀不能为空' }]"
          >
            <el-select v-model="formRule.prefixion" placeholder="请选择" @change='selectChange'>
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <template v-if="this.prefixValue === '4'">
            <el-form-item
              label="应用表单"
              prop="applyForm"
              :rules="[{ required: true, message: '应用表单不能为空' }]"
            >
              <el-select v-model="formRule.applyForm" placeholder="请选择" @change='applyChange'>
                <el-option
                  v-for="item in applyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="关联表单"
              prop="associatedForm"
              :rules="[{ required: true, message: '关联表单不能为空' }]"
            >
              <el-select v-model="formRule.associatedForm" placeholder="请选择" @change='associatedChange'>
                <el-option
                  v-for="item in associatedOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-input style="width:30%;display:none" v-model="formRule.layout"></el-input>
            <div style="margin-left: 10px">
              <el-select v-model="formRule.applyField" placeholder="请选择应用表单字段" :style="{width: '40%'}">
                <el-option
                  v-for="(item, index) in applyFieldOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span style="margin:0 5px">值等于</span>
              <el-select v-model="formRule.associatedField" placeholder="请选择关联表单字段" :style="{width: '40%'}">
                <el-option
                  v-for="(item, index) in associatedFieldOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span style="margin-left:5px">的值</span>
            </div>
            <div style="margin: 10px 0 0 10px">
              <div style="width:120px;height:36px;border:1px solid #DCDFE6;border-radius:4px;padding:8px 30px;display:inline-block" >编码字段</div>
              <span style="margin:0 5px">关联显示</span>
              <el-select v-model="formRule.showAssociated" placeholder="请选择关联表单字段" :style="{width: '40%'}">
                <el-option
                  v-for="(item, index) in associatedFieldOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span style="margin-left:5px">中对应的值</span>
            </div>
          </template>
          <template v-else>
            <el-form-item
              label="格式"
              prop="layout"
              :rules="[{ required: true, message: '格式不能为空' }]"
            >
              <el-input
                v-model="formRule.layout"
                autocomplete="off"
                v-if='!showWhat'
              />
              <el-select v-model="formRule.layout" placeholder="请选择"  v-if='showWhat' @change="shiftChange">
                  <el-option
                    v-for="item in selectOp"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="步长" prop="stepSize" >
              <el-input disabled v-if="prefixValue!=='3'"/>
              <el-input-number 
                v-else
                v-model="formRule.stepSize" 
                controls-position="right"  
                :min="1"
                autocomplete="off"
                placeholder="请输入正整数"
                style='width:100%;textAlign:left'
                onkeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
              />
            </el-form-item>
            <el-form-item label="初始" prop="initialValue" :rules="{ validator: this.prefixValue ==='3' && formRule.initialValue !== ''?validatePass2:'', trigger: 'blur' }">
              <el-input disabled v-if="prefixValue!=='3'"/>
              <el-input
                v-else
                type="number" 
                v-model="formRule.initialValue"
                controls-position="right"  
                autocomplete="off"
                placeholder="请按照所选格式填写"
                style='width:100%;textAlign:left'
                onkeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))"
              />
            </el-form-item>
            <el-form-item label="说明" prop="description" >
              <el-input v-model="formRule.description" autocomplete="off" />
            </el-form-item>
          </template>
          <div class="button">
            <el-button @click="closeRule">取消</el-button>
            <el-button type="primary" @click='onSaveRules'>确定</el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
  </el-dialog>
</template>

<script>
import {
  editAutoCode,
  addAutoCode,
  addCodeDetails,
  getCodeRules,
  updateCodeRules,
  deleteCodeRules
} from "@/api/custom/autoCoding";
import {
    getNoRepeatFormName,
    getFieldNameList,
    sourceTestList
  } from '@/api/custom/formDesigner'
import {selectOptions} from './config.js'
export default {
  data() {
    return {
      applyTableName:'',
      associatedTableName:'',
      formModel:{
        encodeNum: "",
        encodeName: "",
        encodeDesc: "",
      },
      formRule:{
        prefixion:'1',
        layout:'',
        stepSize:'',
        initialValue:'',
        description:'',
        applyForm:'',
        associatedForm:'',
        applyField:'', 
        associatedField:'',
        showAssociated:'',
      },
      showWhat:false,
      visible: false,
      title:'',
      ruleTitle:'',
      prefixValue:'1',
      drawer:false,
      tableData:[],
      options:[
        {
          value: '1',
          label: '自定义'
        },
        {
          value: '2',
          label: '日期'
        }, 
        {
          value: '3',
          label: '流水号'
        },
        {
          value: '4',
          label: '数据关联'
        }
      ],
      applyOptions:[],//应用表单
      associatedOptions:[],//关联表单
      applyFieldOptions:[],//应用表单字段
      associatedFieldOptions:[],//应用表单字段
      selectOptions:selectOptions,
      selectOp:[],
      currentRow:null,
      islight:false,
      validatePass2:(rule, value, callback) => {    
        if(this.formRule.initialValue === undefined){
          callback();
        }else if (this.formRule.initialValue.toString().length !== this.formRule.layout.length) {
          callback(new Error('初始值长度需跟格式保持一致'));
        }else{
          callback();
        }  
      }
    };
  },
  props: ['codingType','editRow','mainChildColumn','childShowHideDate'],
  mounted() {
    if(this.editRow){
      this.formModel.encodeNum=this.editRow.encodeNum
      this.formModel.encodeName=this.editRow.encodeName
      this.formModel.encodeDesc=this.editRow.encodeDesc
      this.title='修改'
      this.getRulesList(this.editRow.id)
    }else{
      this.title='添加'
    }

    //获取应用表单下拉选项数组
    getNoRepeatFormName().then((res) => {
      if (res.code === 0) {
        this.applyOptions = res.data.map((item) => {
          return {
            label: item.name,
            value: item.id
          }
        })
      }
    }).catch(e => {console.log(e);})
  },
  watch:{
    // 'formRule.prefixion':{
    //   handler(){
    //      this.formRule.layout=''
    //   }
    // },
  },
  methods: {
    shiftChange(){   
      this.formRule.initialValue = undefined;   
      this.$refs.refRule.clearValidate(['initialValue'])  
    },
    dialogDrawer(){
      this.$parent.drawerClick('child')
    },
    async deleteRule(){
      if(!this.currentRow){
        this.$message({
          message: '请选择一条数据！',
          type: 'warning'
        });
        return
      }
      if(this.currentRow.id){
        await deleteCodeRules(this.currentRow.id)
         this.getRulesList(this.editRow.id)
         this.currentRow=null
      }else{
        this.tableData=this.tableData.filter(item=>item.key!==this.currentRow.key)
        this.currentRow=null
      }
     
    },
    // 单选事件
    tableClick(row){
      this.islight = true;
      this.currentRow=row
      row.applyForm = parseInt(row?.applyForm,10)
      row.associatedForm = parseInt(row?.associatedForm,10)
    },
    async getRulesList(id){
      const {data}=await getCodeRules(id)
      if(data instanceof Array){
          this.tableData=data
      }else{
        this.tableData.push(data)
      }
    },
    selectChange(val){
      this.$refs.refRule.clearValidate({...this.formRule})
      this.formRule.initialValue = ''
      this.prefixValue=val
      this.formRule.layout = ''
      this.formRule.applyForm = ''
      this.formRule.associatedForm = ''
      this.formRule.applyField =''
      this.formRule.associatedField = ''
      this.formRule.showAssociated =''
      if(val==='1') {
        this.showWhat=false
      }else if(val==='4'){
        this.formRule.layout = '动态数据源'
        // getNoRepeatFormName(params).then((res) => {
        //   if (res.code === 0) {
        //     this.applyOptions = res.data.map((item) => {
        //       return {
        //         label: item.name,
        //         value: item.id
        //       }
        //     })
        //   }
        // }).catch(e => {console.log(e);})
      }else{
        this.showWhat=true
        this.selectOp=this.selectOptions[val]
      }
      this.formRule.stepSize=undefined
      this.formRule.initialValue=undefined
      this.formRule.description=''
    },
    //应用表单下拉选中操作
    applyChange(val){
      this.applyTableName = val
      this.formRule.associatedForm = ''
      this.formRule.applyField =''
      this.formRule.associatedField = ''
      let params ={
        excludeId:val
      }
      //获取做筛选后关联表单下拉选项数组
      getNoRepeatFormName(params).then((res) => {
        if (res.code === 0) {
          this.associatedOptions = res.data.map((item) => {
            return {
              label: item.name,
              value: item.id
            }
          })
        }
      }).catch(e => {console.log(e);})

      //获取应用表单字段
      sourceTestList(val).then((res) => {
        if (res.code === 0) {
          this.applyFieldOptions = res.data.columns.map((item) => {
            return {
              label: item.name,
              value: item.name
            }
          })
        }
      }).catch(e => {console.log(e);})
    },
    //关联表单下拉选中操作
    associatedChange(val){
      this.associatedTableName = val

      //获取关联表单字段
      sourceTestList(val).then((res) => {
        if (res.code === 0) {
          this.associatedFieldOptions = res.data.columns.map((item) => {
            return {
              label: item.name,
              value: item.name
            }
          })
        }
      }).catch(e => {console.log(e);})
      
    },
    onSaveCode(){
       this.$refs.formTop.validate(async(valid) => {
          if (valid) {
            const param={
              id:this.editRow?this.editRow.id:undefined,
              ...this.formModel
            }
            if(this.editRow){
                if(this.tableData.length!==0){
                 const params=this.tableData.filter(item=>!item.encodeId).map(item=>{
                  return {
                    encodeId:this.editRow.id,
                    ...item
                  }
                })
                 addCodeDetails(params)
              }
               //编辑
               editAutoCode(param).then((res) => {
                this.$emit('closeDialog')
                this.$emit('getList')
               }).catch(e => {
               })
            }else{
               const {data,code,msg} = await addAutoCode(param)
                if(this.tableData.length!==0){
                const params=this.tableData.map(item=>{
                  return {
                    encodeId:data,
                    ...item
                  }
                })
                 addCodeDetails(params)
              }
              this.$emit('closeDialog')
              this.$emit('getList')
            }
           
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    onSaveRules(){
      const that=this
      this.$refs.refRule.validate((valid) => {
          if (valid) {
           this.closeRule()
           // 编辑编码详情
           if(that.ruleTitle==='编辑'){
             const param={
               id:that.currentRow.id,
               ...that.formRule
             }
            if(this.currentRow.id){
              updateCodeRules(param).then((res)=>{
                if(res.data){
                  that.getRulesList(that.editRow.id)
                }
              })
            }else{
              that.tableData=that.tableData.map(item=>{
                if(item.key===that.currentRow.key){
                  return {
                    ...item,
                    ...that.formRule
                  }
                }
                return item
              })
             that.currentRow={key:that.currentRow.key,...that.formRule}
            }
           }else{
             console.log(that.formRule)
              that.tableData.push({...that.formRule,key:Date.now()})
           }
           this.islight = false;
           this.currentRow=null;
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    cancel(val){
      if(val==='rule'){
        this.visible=false
        return
      }
      this.$emit('closeDialog')
    },
    closeRule(){
      this.visible=false
    },
    addCodingRule() {
      this.visible = true;
      this.ruleTitle='新增'
      this.formRule.prefixion='1'
      this.formRule.layout=''
      this.formRule.stepSize  =''
      this.formRule.initialValue  =''
      this.formRule.description  =''
      this.showWhat=false
      this.prefixValue = '1';
    },
    editRule(){
      this.formRule.layout = ''
      this.formRule.applyForm = ''
      this.formRule.associatedForm = ''
      this.formRule.applyField =''
      this.formRule.associatedField = ''
      this.formRule.showAssociated =''
      if(this.tableData.length===0){
        this.$message({
          message: '请选择一条数据！',
          type: 'warning'
        });
        return
      }
      if(!this.currentRow){
        this.$message({
          message: '请选择一条数据！',
          type: 'warning'
        });
        return
      }
      this.visible = true;
      this.ruleTitle='编辑'
      if(this.currentRow.prefixion === '4'){
        //获取做筛选后关联表单下拉选项数组
      
        //获取编辑界面关联表单下拉选项数组
        getNoRepeatFormName(this.currentRow.applyForm).then((res) => {
          if (res.code === 0) {
            this.associatedOptions = res.data.map((item) => {
              return {
                label: item.name,
                value: item.id
              }
            })
          }
        }).catch(e => {console.log(e);})

        //获取应用表单字段
        sourceTestList(this.currentRow.applyForm).then((res) => {
          if (res.code === 0) {
            this.applyFieldOptions = res.data.columns.map((item) => {
              return {
                label: item.name,
                value: item.name
              }
            })
          }
        }).catch(e => {console.log(e);})
        //获取关联表单字段
        sourceTestList(this.currentRow.associatedForm).then((res) => {
          if (res.code === 0) {
            this.associatedFieldOptions = res.data.columns.map((item) => {
              return {
                label: item.name,
                value: item.name
              }
            })
          }
        }).catch(e => {console.log(e);})
      }
      
      
      this.formRule.prefixion=this.currentRow.prefixion,
      this.formRule.stepSize  =this.currentRow.stepSize
      this.formRule.initialValue  =this.currentRow.initialValue
      this.formRule.description  =this.currentRow.description
      this.formRule.layout = this.currentRow.layout
      this.formRule.applyForm = this.currentRow.applyForm
      this.formRule.associatedForm = this.currentRow.associatedForm
      this.formRule.applyField = this.currentRow.applyField
      this.formRule.associatedField = this.currentRow.associatedField
      this.formRule.showAssociated = this.currentRow.showAssociated
      this.prefixValue='1';
      this.$nextTick(()=>{
         if(this.formRule.prefixion==='1'){
          this.showWhat=false
          }else{
            this.showWhat=true
            this.selectOp=this.selectOptions[this.currentRow.prefixion]
          }
          if(this.currentRow.prefixion==='3'){
            this.prefixValue='3'
          }
         if(this.currentRow.prefixion==='4'){
           
            this.prefixValue='4'
             this.formRule.layout='动态数据源'
          }
        this.formRule.layout=this.currentRow.layout
      })
    }
  },
};
</script>

<style lang="less" scoped>
.choiceList {
  border: 1px dashed;
  height: 50px;
  padding: 10px 20px;
}
.choiceList .el-tag + .el-tag {
  margin-left: 10px;
}
.treeContent {
  display: flex;
  margin-top: 20px;
}
.button {
  text-align: right;
  margin-top: 20px;
}
.btnCen {
  padding: 0 20px;
  margin: 10px 0;
  display: flex;
  justify-content: space-between;
}
.explicit {
  width: 1.875rem;
  height: 1.875rem;
  border: .0625rem solid grey;
  border-radius: 50%;
  display: inline-block;
  text-align: center;
  margin-left: .625rem;
  line-height: 1.75rem;
  vertical-align: middle;
  font-size: 1rem;
}
.el-input__inner {
  text-align: left !important; 
}
/deep/.el-input-number .el-input__inner {
    text-align: left;
}
</style>
